﻿using _15Net8AspNetCore_ORM.Context;
using _15Net8AspNetCore_ORM.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace _15Net8AspNetCore_ORM.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EFCoreOrderController : ControllerBase
    {
        public EFCoreDBContext _EFCoreDB { get; set; }
        public EFCoreOrderController(EFCoreDBContext eFCoreDB)
        {
            _EFCoreDB = eFCoreDB;
        }


        /// <summary>
        /// 新增商品
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> AddOrder(Order Order)
        {
            await _EFCoreDB.Order.AddAsync(Order);
            await _EFCoreDB.SaveChangesAsync();
            return CreatedAtAction(nameof(GetOrder), new { id = Order.Id }, Order);
        }


        /// <summary>
        /// 删除商品
        /// </summary>
        [HttpDelete("id")]
        public async Task<IActionResult> DeleteOrder(int id)
        {
            Order Order = await _EFCoreDB.Order.FirstOrDefaultAsync(T => T.Id == id);
            if (Order != null)
            {
                _EFCoreDB.Order.Remove(Order);
                await _EFCoreDB.SaveChangesAsync();
                return Ok("删除成功");
            }
            else
            {
                return NotFound();
            }
        }

        /// <summary>
        /// 修改商品
        /// </summary>
        [HttpPut("id")]
        public async Task<IActionResult> UpdateOrder(int id, Order Order)
        {

            //1、设置更新状态
            _EFCoreDB.Entry(Order).State = EntityState.Modified;
            try
            {
                await _EFCoreDB.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw;
            }
            return Ok("更新成功");
        }

        /// <summary>
        /// 获取商品
        /// </summary>
        [HttpGet("id")]
        public async Task<IActionResult> GetOrder(int id)
        {
            Order Order = await _EFCoreDB.Order.FirstOrDefaultAsync(T => T.Id == id);
            return Ok(Order);
        }

        /// <summary>
        /// 获取商品
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAllOrder()
        {
            List<Order> orders = _EFCoreDB.Order.ToList();
            return Ok(orders);
        }
    }
}

